<template>
    <div class="userContianer">
        <el-breadcrumb separator="/">
            <el-breadcrumb-item>首页</el-breadcrumb-item>
            <el-breadcrumb-item>数据监测</el-breadcrumb-item>
            <el-breadcrumb-item>短信管理</el-breadcrumb-item>
        </el-breadcrumb>
        <div class="tool">
            <el-button type="success" @click="addUser" style="margin-right: 10px;">添加用户</el-button>
            <div class="search">
                <el-input v-model="queryParmas.keyword" clearable placeholder="搜索用户"></el-input>
            </div>
            <el-button type="primary" @click="toSearch" class="query">查询</el-button>
        </div>
       <!-- 数据列表 -->
       <div class="table">
            <el-table 
                :data="userList"
                border 
                stripe
           >

                <el-table-column v-for="(item,index) in propList" :key="index" :prop="item.prop" :label="item.label" >
                    <template v-if="item.prop == 'isWatch'" #default="{row}">
                        <el-switch
                            v-model="row.isWatch"
                            @change="changeWitch(row.rid,row.isWatch)"
                            class="mt-2"
                            style="margin-left: 24px"
                            inline-prompt
                            :active-icon="Check"
                            :inactive-icon="Close"
                        />
                    </template>
                </el-table-column>
                <!-- 用户创建时间 -->
                <el-table-column width="160px">
                    <template #header>
                        创建时间
                    </template>
                    <template #default="{row}">
                        {{ filterDate(row.createdAt)  }}
                    </template>
                </el-table-column>
                <!-- 修改时间 -->
                <el-table-column width="160px">
                    <template #header>
                        修改时间
                    </template>
                    <template #default="{row}">
                        {{ filterDate(row.updatedAt) }}
                    </template>
                </el-table-column>
                <!-- 操作 -->
                <el-table-column label="操作">
                    <template #default="{row}">
                        <el-button type="warning" :icon="Edit" @click="editUser(row)"></el-button>
                        <el-popconfirm title="Are you sure to delete this?" @confirm="removeUser(row.rid)">
                            <template #reference>
                                <el-button type="danger" :icon="Delete"></el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
           </el-table>
             <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="queryParmas.pageSize"
                :page-sizes="[10, 15, 20]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </div>
    </div>
    <!-- 添加用户对话框 -->
    <el-dialog
        draggable       
        v-model="userVisible"
        title="添加用户"
        width="30%"
        @close="closeDialog"
     >
     <el-form
        label-width="100px"
        :model="userInfo"
        style="max-width: 460px"
        :rules="userFormRules"
        ref="userAddRef"
  >
    <el-form-item label="用户名称：" prop="username">
      <el-input v-model="userInfo.username" />
    </el-form-item>
    <el-form-item label="手机号码：" prop="phone">
      <el-input v-model="userInfo.phone" />
    </el-form-item>
  </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="userVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAddUser">
          添加
        </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 修改用户对话框 -->
  <el-dialog
    draggable
    v-model="updateVisible"
    ref="userUpdateRef"
    title="修改用户"
    width="30%"
    @close="closeDialog1"
  >
  <el-form
        label-width="100px"
        :model="updateUserInfo"
        style="max-width: 460px"
        :rules="userFormRules1"
        ref="userUpdateRef"
  >
    <el-form-item label="用户名称：" prop="username">
      <el-input v-model="updateUserInfo.username" />
    </el-form-item>
    <el-form-item label="手机号码：" prop="phone">
      <el-input v-model="updateUserInfo.phone" />
    </el-form-item>
  </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="updateVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmUpdateUser">
          修改
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
    import {ref,reactive, getCurrentInstance,onMounted} from 'vue'
    import {Edit,Delete,Check,Close} from '@element-plus/icons-vue'
import { adminStore } from '../../store/admin';
    
    let userVisible = ref(false) // 控制添加用户对话框
    let updateVisible = ref(false) // 控制修改用户对话框

    // 导入手机监测列表
    let admin_store = adminStore()
    let {proxy} = getCurrentInstance()
    const queryParmas = reactive({
        pageSize: 10,
        page: 1,
        keyword: "" // 查询关键字
    })
    const userInfo = reactive({
        username: "",
        phone: ""
    })
    const updateUserInfo = reactive({
        username: "",
        phone: ""
    })
    let total = ref(0) // 总数
    let currentPage = ref(1) // 初始页
    let userList = reactive([]) // 用户列表
    let userAddRef = ref() 
    let userUpdateRef = ref() 
    // 添加用户
    const addUser = async () => {
        userVisible.value = true
    }
    // 切换是否开启短信提醒
    const changeWitch = async (rid:number,bool:boolean) => {
        let {data:res} = await proxy.$adminHttp.put('/user/updateUser',{
            rid,
            isWatch: bool
        })
       if (res.code !== 200) return proxy.$message({showClose: true,message: res.msg,type: "warning"})
       proxy.$message({showClose: true,message: bool? "开启短信提醒": "关闭短信提醒",type:"success"})
    
         // 重新初始化手机列表到pinia中
         admin_store.initPhoneList()
         
    }
    // 搜索用户
    const toSearch = () => {
        console.log(queryParmas)
        getUserList()
    }
    onMounted(() => {
        getUserList()
    })
    // 确认添加用户
    const confirmAddUser = async () => {
         userAddRef.value.validate(async (item:any) => {
            if (!item) return proxy.$message({showClose: true,message: "按照规则进行填写",type: "warning"})
            let {data:res} = await proxy.$adminHttp.post("/user/addUser",userInfo)
            if (res.code !== 200) return proxy.$message({showClose: true,message: res.msg,type: "warning"})
            proxy.$message({showClose: true,message: "添加用户成功",type:"success"})
            userVisible.value = false
            getUserList()
            // 重新初始化手机列表到pinia中
            admin_store.initPhoneList()
         })
    }
    // 确认修改用户
    const confirmUpdateUser = () => {
        userUpdateRef.value.validate(async (item:any) => {
            if (!item) return proxy.$message({showClose: true,message: "按照规则进行填写",type: "warning"})
            let res = await proxy.$adminHttp.put("/user/updateUser",{
                rid: editRid.value,
                ...updateUserInfo
            })
           if (res.data.code !== 200) return proxy.$message({showClose: true,message: "修改失败",type: "info"})
           updateVisible.value = false
           proxy.$message({showClose: true,message: "修改成功",type: "success"})
           getUserList()
            // 重新初始化手机列表到pinia中
            admin_store.initPhoneList()
        })
    }
    const removeUser = async (rid:number) => {
        let {data:res} = await proxy.$adminHttp.delete("/user/removeUser?rid=" + rid)
        if (res.code !== 200) return proxy.$message({showClose: true,message: res.msg,type: "warning"})
        proxy.$message({showClose: true,message: "删除用户成功",type:"success"})
        getUserList()
        // 重新初始化手机列表到pinia中
        admin_store.initPhoneList()
    }
    let editRid = ref(0)
    // 编辑用户信息
    let editUser = (row)  => {
        updateVisible.value = true
        updateUserInfo.phone = row.phone
        updateUserInfo.username = row.username
        editRid.value = row.rid
        
    }
    const propList = [
        {
           prop: "rid",
           label: "#"
        },
        {
            prop: "username",
            label: "用户名"
        },
        {
            prop: "phone",
            label: "手机号"
        },
        {
            prop: "isWatch",
            label: "短信提醒"
        }
    ]

    // 对时间函数的过滤
    let filterDate = (date:Date) => {
        return new Date(date).toLocaleDateString().replace(/\//g,"-")+' ' + new Date(date).toLocaleTimeString()
    }   
    const handleSizeChange = () => {

    }
    const handleCurrentChange = () => {

    }
    // 获取用户列表
    const getUserList = async () => {
      let {data:res}:{data:IhttpReturn} = await proxy!.$adminHttp.get('/user/getUserList',{
            params: queryParmas
        })
        total.value = res.total
        userList = res.data
    }
    // 验证用户
  const validateUser = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('用户名不能为空'))
    } else if (!(/^[a-zA-Z0-9_-]{4,16}$/.test(value))) {
        callback(new Error("4到16位（字母，数字，下划线，减号"))
    } else {
        callback()
    }
   }
   // 验证手机号
   const validatePhone = (rule:any,value:any,callback:any) => {
         if (value === '') {
            callback(new Error("手机号不能为空"))
         } else if (!(/^1[3,4,5,6,7,8,9][0-9]{9}$/).test(value)) {
             callback(new Error("请添加正确的手机号"))
         } else {
            callback()
         }
   }
   let userFormRules = reactive({
    username: [{ validator: validateUser, trigger: 'blur' }],
    phone: [{ validator: validatePhone, trigger: 'blur' }],
  })

  let userFormRules1 = reactive({
    username: [{ validator: validateUser, trigger: 'blur' }],
    phone: [{ validator: validatePhone, trigger: 'blur' }],
  })

  let closeDialog = () => {
    // 关闭对话框
    userAddRef.value.resetFields()
  }
  let closeDialog1 = () => {
    // 关闭对话框
    userUpdateRef.value.resetFields()
  }
</script>

<style scoped lang="less">
    .tool {
        display: flex;
        align-items: center;
        margin-top: 20px;
    .search {
        margin-right: 20px;
        .add {
            margin-right: 10px;
        }
        .query {
            margin-left: 10px;
        }
     }
   }
   .table {
    margin-top: 20px;
   }
   .el-pagination {
        margin-top: 10px;
        display: flex;
        justify-content: center;
     }
</style>